import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../common/api/index.dart';
import '../../common/models/index.dart';
import '../../common/style/index.dart';
import '../../common/widgets/index.dart';
import '../common/portal/index.dart';
import 'apps/index.dart';
import 'contact/index.dart';
import 'default_index/index.dart';
import 'im/index.dart';
import 'index.dart';
import 'settings/index.dart';

class HomePage extends GetView<HomeController> {
  const HomePage({Key? key}) : super(key: key);

  /// 底部 tabBar
  Widget _buildBottomNavigationBar() {
    return Obx(() => BottomNavigationBar(
          items: controller.state.homeTabList.map((element) {
            switch (element) {
              case AppIndexModule.im:
                return BottomNavigationBarItem(
                    icon: O2UI.badgeView(controller.state.unReadNumber,
                        const Icon(O2IconFont.message)),
                    activeIcon: O2UI.badgeView(controller.state.unReadNumber,
                        const Icon(O2IconFont.message)),
                    label: element.name());
              case AppIndexModule.contact:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.addressList),
                    activeIcon: const Icon(O2IconFont.addressList),
                    label: element.name());
              case AppIndexModule.home:
                return _indexBarItem();
              case AppIndexModule.app:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.apps),
                    activeIcon: const Icon(O2IconFont.apps),
                    label: element.name());
              case AppIndexModule.settings:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.settings),
                    activeIcon: const Icon(O2IconFont.settings),
                    label: element.name());
            }
          }).toList(),
          currentIndex: controller.state.currentIndex,
          type: BottomNavigationBarType.fixed,
          onTap: (value) => controller.handleNavBarClick(value),
        ));
  }

  Widget _bottomAppbar(BuildContext context) {
    return Obx(() => BottomAppBar(
          padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 12.0),
          height: 80,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: controller.state.homeTabList.asMap().keys.map((index) {
              final element = controller.state.homeTabList[index];
              switch (element) {
                case AppIndexModule.im:
                  return _bottomAppbarItem(
                      context,
                      index,
                      element.name(),
                      O2UI.badgeView(
                          controller.state.unReadNumber,
                          Icon(O2IconFont.message,
                              color: Theme.of(context)
                                  .textTheme
                                  .bodySmall
                                  ?.color)),
                      O2UI.badgeView(
                          controller.state.unReadNumber,
                          Icon(O2IconFont.message,
                              color: Theme.of(context).colorScheme.primary)));
                case AppIndexModule.contact:
                  return _bottomAppbarItem(
                      context,
                      index,
                      element.name(),
                      Icon(O2IconFont.addressList,
                          color: Theme.of(context).textTheme.bodySmall?.color),
                      Icon(O2IconFont.addressList,
                          color: Theme.of(context).colorScheme.primary));
                case AppIndexModule.app:
                  return _bottomAppbarItem(
                      context,
                      index,
                      element.name(),
                      Icon(O2IconFont.apps,
                          color: Theme.of(context).textTheme.bodySmall?.color),
                      Icon(O2IconFont.apps,
                          color: Theme.of(context).colorScheme.primary));
                case AppIndexModule.settings:
                  return _bottomAppbarItem(
                      context,
                      index,
                      element.name(),
                      Icon(O2IconFont.settings,
                          color: Theme.of(context).textTheme.bodySmall?.color),
                      Icon(O2IconFont.settings,
                          color: Theme.of(context).colorScheme.primary));
                case AppIndexModule.home:
                  return _bottomAppbarItem(
                      context,
                      index,
                      '',
                      ProgramCenterService.to.homeBlurImageView(),
                      ProgramCenterService.to.homeFocusImageView());
              }
            }).toList(),
          ),
        ));
  }

  /// 底部导航栏按钮
  Widget _bottomAppbarItem(BuildContext context, int index, String label,
      Widget icon, Widget activeIcon) {
    return Expanded(
        flex: 1,
        child: InkWell(
            onDoubleTap: () => controller.handleNavBarDoubleClick(index),
            onTap: () => controller.handleNavBarClick(index),
            child: Obx(() => Column(mainAxisSize: MainAxisSize.min, children: [
                  controller.state.currentIndex == index ? activeIcon : icon,
                  const SizedBox(height: 5),
                  if (label.isNotEmpty)
                    Text(label,
                        style: controller.state.currentIndex == index
                            ? Theme.of(context).textTheme.bodySmall?.copyWith(
                                color: Theme.of(context).colorScheme.primary)
                            : Theme.of(context).textTheme.bodySmall)
                ]))));
  }

  // 主视图
  Widget _buildView() {
    return Obx(() => controller.state.showBottomBar
        // ? controller.getViewByIndex(controller.state.currentIndex)
        ? _mainPageView()
        : const CircularProgressIndicator());
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeController>(
      builder: (_) {
        return WillPopScope(
            onWillPop: controller.onWillPop,
            child: Obx(() => Scaffold(
                  backgroundColor: Theme.of(context).primaryColor,
                  body: SafeArea(
                    child: _buildView(),
                  ),
                  bottomNavigationBar: controller.state.showBottomBar
                      ? _bottomAppbar(context)
                      : Container(
                          color: Colors.white,
                          width: MediaQuery.of(context).size.width),
                )));
      },
    );
  }

  /// 首页 底部  tab  按钮
  BottomNavigationBarItem _indexBarItem() {
    return BottomNavigationBarItem(
        icon: ProgramCenterService.to.homeBlurImageView(),
        activeIcon: ProgramCenterService.to.homeFocusImageView(),
        label: '');
  }

  /// PageView 主页
  Widget _mainPageView() {
    return Obx(() => PageView.builder(
        controller: controller.pageController,
        itemCount: controller.state.homeTabList.length,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          final app = controller.state.homeTabList[index];
          switch (app) {
            case AppIndexModule.im:
              return KeepAliveWrapper(child: _imPageView());
            case AppIndexModule.contact:
              return KeepAliveWrapper(child: _contactPageView());
            case AppIndexModule.home:
              return KeepAliveWrapper(child: _defaultIndexPageView());
            case AppIndexModule.app:
              return KeepAliveWrapper(child: _appsPageView());
            case AppIndexModule.settings:
              return KeepAliveWrapper(child: _settingsPageView());
          }
        }));
  }

  /// 应用页面
  Widget _appsPageView() {
    AppsBinding().dependencies();
    return const AppsPage();
  }

  /// 通讯录页面
  Widget _contactPageView() {
    ContactBinding().dependencies();
    return const ContactPage();
  }

  /// 首页
  Widget _defaultIndexPageView() {
    var portalId = ProgramCenterService.to.homeIndexPage();
    if (portalId != null && portalId.isNotEmpty) {
      final extendParam = ProgramCenterService.to.appStyle?.extendParam ?? {};
      final indexPortalHiddenAppBar =
          extendParam['indexPortalHiddenAppBar'] ?? true;
      final indexPortalAppBarTitle =
          extendParam['indexPortalAppBarTitle'] ?? 'home_tab_index'.tr;
      Get.lazyPut<PortalController>(
          () => PortalController(initMap: {
                "portalId": portalId,
                "hiddenAppBar": indexPortalHiddenAppBar,
                "title": indexPortalAppBarTitle
              }),
          tag: 'index_tag_$portalId');
      return PortalPage(tag: 'index_tag_$portalId');
    } else {
      DefaultIndexBinding().dependencies();
      return const DefaultIndexPage();
    }
  }

  /// 消息页面
  Widget _imPageView() {
    ImBinding().dependencies();
    return const ImPage();
  }

  /// 设置页面
  Widget _settingsPageView() {
    SettingsBinding().dependencies();
    return const SettingsPage();
  }
}
